package com.mioto.ld.module.network.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.mioto.ld.communication.mqtt.MqttClientConnect;
import com.mioto.ld.communication.mqtt.MqttHelper;
import com.mioto.ld.module.network.model.NetworkPagerVO;
import org.springframework.stereotype.Service;

import com.mioto.ld.module.network.dao.NetworkDao;
import com.mioto.ld.module.network.model.Network;
import com.mioto.ld.module.network.service.INetworkService;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 * @author mioto
 * @date 2024-05-06 10:32:49
 */
@Service("networkService")
public class NetworkServiceImpl implements INetworkService{

    @Resource
    private NetworkDao networkDao;

    @Override
    public List<Network> findList(Network network) {
        return networkDao.findList(network);
    }

    @Override
    public int insert(Network network) {
        network.initCreateData();
        int result = networkDao.insertIgnoreNull(network);
        if (result > 0) {
            MqttHelper.start(network);
        }
        return result;
    }

    @Override
    public int update(Network network) {
        return networkDao.update(network);
    }

    @Override
    public int updateIgnoreNull(Network network) {
        int result = networkDao.updateIgnoreNull(network);
        if (result > 0) {
           if (MqttHelper.mqttClients.containsKey(network.getId())){
               MqttClientConnect mqttClientConnect = MqttHelper.getClient(network.getId());
               mqttClientConnect.close();
               MqttHelper.start(network);
           }
        }
        return result;
    }

    @Override
    public Network findByColumn(String column, Object value) {
        return networkDao.findByColumn(column,value);
    }

    @Override
    public int deleteByColumn(String column, Object value) {
        Network network = findByColumn(column,value);
        if (ObjectUtil.isNotNull(network)){
            MqttClientConnect mqttClientConnect = MqttHelper.getClient(network.getId());
            if (ObjectUtil.isNotNull(mqttClientConnect)){
                mqttClientConnect.close();
                MqttHelper.mqttClients.remove(network.getId());
            }
        }
        return networkDao.deleteByColumn(column,value);
    }

    @Override
    public int batchDelete(Integer[] ids) {
        return networkDao.batchDelete(ids);
    }

    @Override
    public List<NetworkPagerVO> findPager(Network network) {
        return networkDao.findPager(network);
    }
}